package com.invengo.module_check;

import android.app.Activity;
import android.app.Application;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.LifecycleOwner;

import com.invengo.module_check.ui.activity.main.MainActivity;

import java.util.function.Consumer;

import java8.util.Optional;
import me.goldze.mvvmhabit.bus.Messenger;
import me.goldze.mvvmhabit.bus.RxBus;
import me.goldze.mvvmhabit.utils.KLog;

public class ActivityLifecycleCallbackImpl implements Application.ActivityLifecycleCallbacks {
    private FragmentLifecycleCallbackImpl fragmentLifecycleCallback;

    @Override
    public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
        if (activity instanceof MainActivity) {
            fragmentLifecycleCallback = new FragmentLifecycleCallbackImpl();
            ((MainActivity) activity).getSupportFragmentManager().registerFragmentLifecycleCallbacks(fragmentLifecycleCallback, true);
        }
    }

    @Override
    public void onActivityStarted(@NonNull Activity activity) {

        int id = activity.getResources().getIdentifier("toolbarRight", "id", activity.getPackageName());
        Optional.ofNullable((TextView) activity.findViewById(id)).ifPresent(textView -> {
            RxBus.getDefault().toObservable((LifecycleOwner) activity, String.class).subscribe(s -> {
                textView.setText(s);
            });
            textView.setOnClickListener(v ->{
                Messenger.getDefault().send(v,"RightClick");
//                RxBus.getDefault().post(v);
            } );
        });
    }

    @Override
    public void onActivityResumed(@NonNull Activity activity) {

    }

    @Override
    public void onActivityPaused(@NonNull Activity activity) {

    }

    @Override
    public void onActivityStopped(@NonNull Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(@NonNull Activity activity) {
        if (activity instanceof MainActivity) {
            ((MainActivity) activity).getSupportFragmentManager().unregisterFragmentLifecycleCallbacks(fragmentLifecycleCallback);
        }
    }
}
